'''

Case Type： 数据库系统
Case Name： 修改数据目录（dn1),备机重建
Create At:  2020/07/1
@zou_jialiang0505328126
Descption:  1. 去掉主机dn1目录下的文件读权限
2. 在备机上重建
3.恢复主机dn1目录权限，删除备机dn1目录读权限
4.备机重建

history：
created： 2020/07/01  created by @wan005
'''
import unittest
import sys
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant


class Rebuildstandby(unittest.TestCase):
    primary_sh = CommonSH()
    standby_sh = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case061.py start------------')
        self.DN1_PATH = macro.DB_INSTANCE_PATH
        self.dbPrimaryDbUser = Node(node='PrimaryDbUser')
        self.dbStandbyNode = Node(node='Standby1DbUser')
        self.com = Common()
        self.Constant = Constant()

    def test_rebuild_standby(self):
        # remove read permission from dn1
        self.log.info("-----------------------remove read permission of primary's dn1-------------------------")
        remove_cmd = "chmod -r  " + self.DN1_PATH
        self.log.info(remove_cmd)
        self.dbPrimaryDbUser.sh(remove_cmd).result()

        # rebuild fail
        self.log.info("---------------------------build fail------------------------------")
        status = self.standby_sh.executeGsctl('build', self.Constant.REBUILD_SUCCESS_MSG)
        self.assertFalse(status)

        self.log.info("------------recover and remove read permission of standby's dn1------------")
        remove_cmd = "chmod 700  " + self.DN1_PATH
        self.log.info(remove_cmd)
        self.dbPrimaryDbUser.sh(remove_cmd).result()
        remove_cmd = "chmod -r  " + self.DN1_PATH
        self.log.info(remove_cmd)
        self.dbStandbyNode.sh(remove_cmd).result()

        self.log.info("---------------------------build fail------------------------------")
        status = self.standby_sh.executeGsctl('build', self.Constant.REBUILD_SUCCESS_MSG)
        self.assertTrue(status)

    def tearDown(self):
        self.log.info('----------------------------this is tearDown------------------------')
        self.log.info('------------------------------recover dn1-------------------------')
        # 此处若用+r则会给属组和其他用户都赋了读权限，而DN1的权限不能高于700
        remove_cmd = "chmod 700 " + self.DN1_PATH
        self.log.info(remove_cmd)
        self.dbPrimaryDbUser.sh(remove_cmd).result()

        remove_cmd = "chmod 700 " + self.DN1_PATH
        self.log.info(remove_cmd)
        self.dbStandbyNode.sh(remove_cmd).result()

        # rebuild success
        status = self.standby_sh.executeGsctl('build', self.Constant.REBUILD_SUCCESS_MSG)
        self.log.info(status)
